package edu.njfu.controller;

import edu.njfu.pojo.Book;
import edu.njfu.pojo.Borrower;
import edu.njfu.service.IBorrowerService;
import edu.njfu.util.AdminException;
import edu.njfu.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/borrower")
public class BorrowerController {
    @Autowired
    private IBorrowerService borrowerService;


    @GetMapping("/list")
    public Result list() {
        try {
            List<Borrower> list = borrowerService.findAll();
            return new Result("查询成功", list);
        } catch (AdminException e) {
            e.printStackTrace();
            return new Result(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误");
        }
    }

    @GetMapping("/updateStatusById")
    public Result updateStatusById(@RequestParam Long id, @RequestParam Integer status) {
        try {
            borrowerService.updateStatusById(id, status);
            if (status == 0) {
                return new Result("启用成功", null);
            }
            return new Result("冻结成功", null);
        } catch (AdminException e) {
            e.printStackTrace();
            return new Result(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误");
        }
    }

    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(Borrower borrower) {
        try {
            if (borrower.getId() != null) {
                borrowerService.updateById(borrower);
                return new Result("更新成功", null);
            }
            // 保存
            borrowerService.save(borrower);
            return new Result("保存成功", null);
        } catch (AdminException e) {
            e.printStackTrace();
            return new Result(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误");
        }
    }

    @GetMapping("/findById")
    public Result editById(@RequestParam Long id) {
        try {
            Borrower borrower = borrowerService.findById(id);
            return new Result("查询成功", borrower);
        } catch (AdminException e) {
            e.printStackTrace();
            return new Result(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误");
        }
    }

    @GetMapping("/deleteById")
    public Result deleteById(@RequestParam Long id) {
        try {
            borrowerService.deleteById(id);
            return new Result("删除成功", null);
        } catch (AdminException e) {
            e.printStackTrace();
            return new Result(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误");
        }
    }
}
